package com.fling.abcde.wxapi;

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fling.abcde.R;
import com.fling.abcde.base.BaseActivity;
import com.fling.abcde.bean.TokenResBean;
import com.fling.abcde.wxapi.utils.WXPersonalInfo;
import com.fling.abcde.wxapi.utils.WxApiUtils;
import com.lib.okhttp.NetRequest;
import com.lib.common.bean.BaseResp;
import com.lib.utils.RegexUtils;
import com.lib.utils.SignUtils;
import com.lib.utils.XLog;
import com.lib.common.view.ClearEditText;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;


public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler, View.OnClickListener {

    private WXPersonalInfo mInfo;
    private AlertDialog mBindPhoneDialog;
    private AlertDialog mNeedBindAccout;
    private TextView mDialogbind;
    private TextView mDialogreg;
    private ClearEditText mPwdnum;
    private ClearEditText mPhonenum;

    // IWXAPI 是第三方app和微信通信的openapi接口
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setFullScreenTranslucent(true);
        setActionBarVisible(false);
        // WXAPIFactory.createWXAPI(this, Config.WX_APP_ID, false).handleIntent(getIntent(), this);
        if (WxApiUtils.sWxApi != null) {
            WxApiUtils.sWxApi.handleIntent(getIntent(), this);
        }
        // showLoading();
    }

    @Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
        setIntent(intent);
        if (WxApiUtils.sWxApi != null) {
            WxApiUtils.sWxApi.handleIntent(getIntent(), this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        XLog.i("返回");
        if (resultCode == RESULT_FIRST_USER) {
            finish();
        }
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(com.tencent.mm.opensdk.modelbase.BaseResp baseResp) {

        switch (baseResp.getType()) {
            //登录回调
            case ConstantsAPI.COMMAND_SENDAUTH:
                SendAuth.Resp resp = (SendAuth.Resp) baseResp;
                switch (resp.errCode) {
                    case com.tencent.mm.opensdk.modelbase.BaseResp.ErrCode.ERR_OK:
                        showLoading();
                        getAccessToken(resp.code);
                        break;
                    case com.tencent.mm.opensdk.modelbase.BaseResp.ErrCode.ERR_AUTH_DENIED:
                    case com.tencent.mm.opensdk.modelbase.BaseResp.ErrCode.ERR_USER_CANCEL:
                        finish();
                        break;
                }
                break;
            case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                finish();
                break;
        }
    }

    private void getAccessToken(String code) {
        //获取授权
        String http = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + WxApiUtils.WX_APP_ID + "&secret=" + WxApiUtils.WX_APP_SECRET
                + "&code=" + code + "&grant_type=authorization_code";
        // mNetManager.doGet(TaskId.GET_WX_TOKEN, http, String.class);
    }

    @Override
    public void onDataChanged(BaseResp baseResp) {

        switch (0) {
            case 1:
                String access = null;
                String openId = null;
                String scope = null;
                try {
                    JSONObject jo = JSON.parseObject(baseResp.getMsg());
                    access = jo.getString("access_token");
                    openId = jo.getString("openid");
                    scope = jo.getString("scope");
                } catch (Exception e) {//
                }
                if (openId == null || access == null) {
                    // 如弹出此提示，说明AppId和密钥有问题
                    hideLoading();
                    Toast.makeText(this, "授权失败，请稍后重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                //获取个人信息
                String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" +
                        openId;
//                mNetManager.doGet(TAG, getUserInfoUrl, WXPersonalInfo.class);
                break;
            case 2:
                mInfo = (WXPersonalInfo) baseResp;

                NetRequest netReqEntity = NetRequest.newInstance();
                NetRequest.Post post = netReqEntity.doPost();
                post.addParamFormBody("open_id", mInfo.getOpenid() + "");
                post.addParamFormBody("sign", SignUtils.getSign((netReqEntity.doPost().getParamFormBody())));
                post.addParamFormBody("timestamp", System.currentTimeMillis() + "");
                mNetManager.doPost(netReqEntity, TokenResBean.class);
                break;
            case 3:
                hideLoading();
                if (baseResp.getCode() == 200) {
                    gotoMain((TokenResBean) baseResp);
                } else {
                    showBindAccount();
                }
                break;
            case 4:
                if (baseResp.getCode() == 200) {
                    gotoMain((TokenResBean) baseResp);
                    break;
                }
        }
    }

    private void gotoMain(TokenResBean bean) {

        // TokenBean.DataEntity data = bean.getData();
        // sUser.setToken(data.getToken());
        // sUser.setUid(data.getUid());
        // sIntent.setClass(this, MainActivity.class);
        // startActivity(sIntent);
        // finish();
    }

    private void showBindAccount() {

        if (mNeedBindAccout == null) {
            final View view = LayoutInflater.from(WXEntryActivity.this).inflate(R.layout.activity_bind_account, null);
            mNeedBindAccout = new AlertDialog.Builder(this).setView(view).setCancelable(false).create();
            TextView title = (TextView) view.findViewById(R.id.bind_title);
            title.setText(String.format("此%s尚未绑定账号，是否绑定已有账号？", "微信"));
            mDialogbind = (TextView) view.findViewById(R.id.dialog_bind);
            mDialogreg = (TextView) view.findViewById(R.id.dialog_reg);
            mPhonenum = (ClearEditText) view.findViewById(R.id.phone_num);
            mPwdnum = (ClearEditText) view.findViewById(R.id.pwd_num);
            mDialogbind.setOnClickListener(this);
            mDialogreg.setOnClickListener(this);
        }
        mNeedBindAccout.show();
    }

    @Override
    public void onClick(View v) {

        int i = v.getId();
        if (i == R.id.dialog_reg) {
            // sIntent.setClass(WXEntryActivity.this, RegistActivity.class);
            // sIntent.putExtra("head_img", mInfo.getHeadimgurl());
            // sIntent.putExtra("openid", mInfo.getOpenid());
            // sIntent.putExtra("nickname", mInfo.getNicknam());
            // sIntent.putExtra("unionid", mInfo.getUnionid());
            // startActivity(sIntent);
            // finish();

        } else if (i == R.id.dialog_bind) {
            if (mDialogbind.getText().toString().contains("开始")) {
                toBind();
                return;
            }
            mPhonenum.setVisibility(View.VISIBLE);
            mPwdnum.setVisibility(View.VISIBLE);
            mDialogbind.setText("开始绑定");

        }
    }

    private void toBind() {

        String phone = mPhonenum.getText().toString().trim();
        String pwd = mPwdnum.getText().toString().trim();
        if (!RegexUtils.isMobileExact(phone)) {
            Toast.makeText(this, "请检查手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "请检查密码", Toast.LENGTH_SHORT).show();
            return;
        }
        NetRequest netReqEntity = NetRequest.newInstance();
        netReqEntity.doPost()
                .addParamFormBody("phone", phone)
                .addParamFormBody("password", pwd)
                .addParamFormBody("open_id", mInfo.getOpenid() + "")
                .addParamFormBody("type", "1")
                .addParamFormBody("sign", SignUtils.getSign((netReqEntity.doPost().getParamFormBody())))
                .addParamFormBody("timestamp", System.currentTimeMillis() + "")
                .doReq(mNetManager, TokenResBean.class);
    }
}